package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Friend;
import com.itheima.service.mongo.FriendService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addContacts(Long userId, Long friendId) {
        //正向userid--friendid
        //构建查询条件
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        Friend friend1 = mongoTemplate.findOne(query1, Friend.class);
        if(friend1==null){//添加
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setCreated(System.currentTimeMillis());
            friend.setFriendId(friendId);
            mongoTemplate.save(friend);
        }

        //反向friendid---userid
        Query query2 = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        Friend friend2= mongoTemplate.findOne(query2,Friend.class);
        if(friend2==null){
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    //分页查询用户的好友列表
    @Override
    public PageBeanVo findContact(Long userId, Integer pageNum, Integer pageSize) {
        // 1.组装查询条件
        Query query = new Query(Criteria.where("userId").is(userId)).skip((pageNum-1)*pageSize).limit(pageSize);

        // 2.执行查询
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        //执行统计
        long count = mongoTemplate.count(query, Friend.class);

        //返回结果
        return new PageBeanVo(pageNum,pageSize,count,friendList);
    }


    //删除好友关系
    @Override
    public void deleteContacts(Long userId, Long likeUserId) {
        //正向
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(likeUserId));
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if(exists1){
            mongoTemplate.remove(query1,Friend.class);
        }

        //反向
        Query query2 = new Query(Criteria.where("userId").is(likeUserId).and("friendId").is(userId));
        boolean exists2 = mongoTemplate.exists(query2, Friend.class);
        if(exists2){
            mongoTemplate.remove(query2,Friend.class);
        }
    }
}
